package network1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpServe {
    private DatagramSocket socket=null;
    public UdpServe(int port){
        try {
            socket=new DatagramSocket(port);
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }
    public void start(){
        System.out.println("服务器启动");
        while(true){
            DatagramPacket requestPacket=new DatagramPacket(new byte[4096],4096);
            try {
                socket.receive(requestPacket );
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String resp=new String(requestPacket.getData(),0,requestPacket.getLength());
            String respon=process(resp);
            DatagramPacket responPack=new DatagramPacket(resp.getBytes(),0,resp.getBytes().length,
                    requestPacket.getSocketAddress());
            try {
                socket.send(responPack);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            System.out.printf("[%s:%d],resp=%s,respon=%s",requestPacket.getAddress(),requestPacket.getPort(),
                    resp,respon);

        }
    }

    private String process(String resp) {
        return resp;
    }

    public static void main(String[] args) {
        UdpServe udpServe=new UdpServe(9090);
        udpServe.start();
    }
}
